/**
 * DeepSeek API 连接器
 * 用于处理与DeepSeek API的通信，包括配置管理、数据请求等功能
 */

class DeepSeekConnector {
    constructor() {
        this.baseUrl = null;
        this.apiKey = null;
        this.apiVersion = 'v1';
        this.defaultModel = 'deepseek-base';
        this.timeout = 30000; // 默认超时时间：30秒
        this.retryCount = 3;  // 默认重试次数
        this.concurrentRequests = 5; // 默认并发请求数
        this.rateLimiter = true; // 默认启用请求频率限制
        this.tokenUsage = {
            prompt: 0,
            completion: 0,
            total: 0
        };
        
        // 读取本地存储的配置
        this.loadConfig();
        
        // 初始化请求队列
        this.requestQueue = [];
        this.activeRequests = 0;
        
        // 设置请求处理器
        this.processQueue();
    }
    
    /**
     * 从本地存储加载配置
     */
    loadConfig() {
        try {
            const config = JSON.parse(localStorage.getItem('deepseek_config'));
            if (config) {
                this.baseUrl = config.apiUrl || this.baseUrl;
                this.apiKey = config.apiKey || this.apiKey;
                this.apiVersion = config.apiVersion || this.apiVersion;
                this.defaultModel = config.defaultModel || this.defaultModel;
                this.timeout = config.requestTimeout || this.timeout;
                this.retryCount = config.retryCount || this.retryCount;
                this.concurrentRequests = config.concurrentRequests || this.concurrentRequests;
                this.rateLimiter = config.enableRateLimiting !== undefined ? config.enableRateLimiting : this.rateLimiter;
                
                console.log('DeepSeek配置已从本地存储加载');
            }
        } catch (error) {
            console.error('加载DeepSeek配置失败:', error);
        }
    }
    
    /**
     * 保存配置到本地存储
     * @param {Object} config 配置对象
     */
    saveConfig(config) {
        try {
            if (config.apiUrl) this.baseUrl = config.apiUrl;
            if (config.apiKey) this.apiKey = config.apiKey;
            if (config.apiVersion) this.apiVersion = config.apiVersion;
            if (config.defaultModel) this.defaultModel = config.defaultModel;
            if (config.requestTimeout) this.timeout = config.requestTimeout * 1000;
            if (config.retryCount !== undefined) this.retryCount = config.retryCount;
            if (config.concurrentRequests) this.concurrentRequests = config.concurrentRequests;
            if (config.enableRateLimiting !== undefined) this.rateLimiter = config.enableRateLimiting;
            
            localStorage.setItem('deepseek_config', JSON.stringify({
                apiUrl: this.baseUrl,
                apiKey: this.apiKey,
                apiVersion: this.apiVersion,
                defaultModel: this.defaultModel,
                requestTimeout: this.timeout / 1000,
                retryCount: this.retryCount,
                concurrentRequests: this.concurrentRequests,
                enableRateLimiting: this.rateLimiter
            }));
            
            console.log('DeepSeek配置已保存到本地存储');
            return true;
        } catch (error) {
            console.error('保存DeepSeek配置失败:', error);
            return false;
        }
    }
    
    /**
     * 测试API连接
     * @returns {Promise} 连接测试结果
     */
    testConnection() {
        return new Promise((resolve, reject) => {
            if (!this.baseUrl || !this.apiKey) {
                reject(new Error('API地址或API密钥未配置'));
                return;
            }
            
            // 在实际环境中，这里应该发送一个轻量级的请求到API进行验证
            // 这里为了演示，使用模拟实现
            
            // 模拟API请求
            setTimeout(() => {
                const success = Math.random() > 0.2; // 80%成功率，模拟连接结果
                
                if (success) {
                    // 更新连接状态为已连接
                    this.updateConnectionStatus(true);
                    resolve({
                        success: true,
                        message: '连接成功',
                        data: {
                            version: this.apiVersion,
                            models: ['deepseek-base', 'deepseek-pro', 'deepseek-expert', 'deepseek-coder', 'deepseek-chat'],
                            maxConcurrentRequests: 10
                        }
                    });
                } else {
                    // 更新连接状态为连接失败
                    this.updateConnectionStatus(false);
                    reject(new Error('API连接失败，服务器无响应'));
                }
            }, 1500);
        });
    }
    
    /**
     * 更新连接状态
     * @param {boolean} isConnected 是否已连接
     */
    updateConnectionStatus(isConnected) {
        const statusElement = $('.connection-status');
        if (statusElement.length) {
            if (isConnected) {
                statusElement.removeClass('bg-danger bg-warning').addClass('bg-success').text('已连接');
            } else {
                statusElement.removeClass('bg-success bg-warning').addClass('bg-danger').text('连接失败');
            }
        }
    }
    
    /**
     * 发送聊天请求
     * @param {Array} messages 消息数组
     * @param {Object} options 请求选项
     * @returns {Promise} 聊天响应结果
     */
    chat(messages, options = {}) {
        if (!this.baseUrl || !this.apiKey) {
            return Promise.reject(new Error('API地址或API密钥未配置'));
        }
        
        const model = options.model || this.defaultModel;
        const temperature = options.temperature !== undefined ? options.temperature : 0.7;
        const max_tokens = options.maxTokens || 2048;
        const top_p = options.topP !== undefined ? options.topP : 0.95;
        const top_k = options.topK || 50;
        const stream = options.stream !== undefined ? options.stream : true;
        
        const payload = {
            model,
            messages,
            temperature,
            max_tokens,
            top_p,
            top_k,
            stream
        };
        
        // 添加请求到队列
        return this.enqueueRequest('chat', payload, stream);
    }
    
    /**
     * 将请求添加到队列
     * @param {string} endpoint API端点
     * @param {Object} payload 请求数据
     * @param {boolean} isStream 是否为流式请求
     * @returns {Promise} 请求结果
     */
    enqueueRequest(endpoint, payload, isStream = false) {
        return new Promise((resolve, reject) => {
            const requestItem = {
                endpoint,
                payload,
                isStream,
                resolve,
                reject,
                retries: 0
            };
            
            this.requestQueue.push(requestItem);
            this.processNextRequest();
        });
    }
    
    /**
     * 处理请求队列
     */
    processQueue() {
        setInterval(() => {
            this.processNextRequest();
        }, 100);
    }
    
    /**
     * 处理下一个请求
     */
    processNextRequest() {
        // 如果没有活跃请求或者活跃请求数小于并发限制，则处理下一个请求
        if (this.requestQueue.length > 0 && this.activeRequests < this.concurrentRequests) {
            const request = this.requestQueue.shift();
            this.activeRequests++;
            
            this.executeRequest(request)
                .catch(error => {
                    if (request.retries < this.retryCount) {
                        console.warn(`请求失败，尝试重试 (${request.retries + 1}/${this.retryCount})...`);
                        request.retries++;
                        this.requestQueue.unshift(request);
                    } else {
                        request.reject(error);
                    }
                })
                .finally(() => {
                    this.activeRequests--;
                    this.processNextRequest();
                });
        }
    }
    
    /**
     * 执行API请求
     * @param {Object} request 请求对象
     * @returns {Promise} 请求结果
     */
    executeRequest(request) {
        // 实际请求处理，由于是模拟环境，这里使用模拟实现
        return new Promise((resolve, reject) => {
            // 在实际环境中，这里应该使用fetch或axios发送真实请求
            // 这里为了演示，使用模拟实现
            
            setTimeout(() => {
                if (request.endpoint === 'chat') {
                    if (request.isStream) {
                        // 模拟流式响应
                        this.simulateStreamResponse(request.payload.messages, request.resolve);
                    } else {
                        // 模拟普通响应
                        this.simulateResponse(request.payload.messages, request.resolve);
                    }
                } else {
                    reject(new Error(`不支持的端点: ${request.endpoint}`));
                }
            }, 500);
        });
    }
    
    /**
     * 模拟API响应（非流式）
     * @param {Array} messages 消息数组
     * @param {Function} resolve Promise解析函数
     */
    simulateResponse(messages, resolve) {
        const lastMessage = messages[messages.length - 1].content;
        let response;
        
        if (lastMessage.includes('道路') || lastMessage.includes('勘察')) {
            response = "根据道路勘察规范，需要考虑地质条件、水文条件和周边环境等因素。建议进行详细的地质勘察，包括钻探取样和土壤分析，以确定道路基础设计参数。同时，应评估排水系统需求和潜在的环境影响。";
        } else if (lastMessage.includes('地质') || lastMessage.includes('岩石')) {
            response = "该区域主要岩石类型为砂岩和页岩，属于沉积岩类别。根据钻探数据，表层0-5米主要为粉质粘土和砂质土，5-15米为强风化砂岩，15米以下为中风化砂岩。地下水位在8-10米左右，季节性波动约1-2米。";
        } else if (lastMessage.includes('水文') || lastMessage.includes('排水')) {
            response = "该区域年均降雨量850mm，集中在6-9月份。根据径流计算，需要设计的排水系统应能应对50年一遇的暴雨强度，建议采用混凝土U型沟进行路面排水，断面尺寸建议不小于40cm×50cm，并设置沉砂池处理路面径流。";
        } else {
            response = "已收到您的问题，作为机勘院DeepSeek助手，我可以提供道路勘察、地质分析和工程设计相关的专业建议。请提供更多具体信息，以便我能给出更准确的专业回答。";
        }
        
        // 模拟token使用统计
        const promptTokens = Math.ceil(lastMessage.length / 4);
        const completionTokens = Math.ceil(response.length / 4);
        
        this.tokenUsage.prompt += promptTokens;
        this.tokenUsage.completion += completionTokens;
        this.tokenUsage.total += (promptTokens + completionTokens);
        
        resolve({
            id: 'chatcmpl-' + Math.random().toString(36).substring(2, 12),
            object: 'chat.completion',
            created: Math.floor(Date.now() / 1000),
            model: this.defaultModel,
            choices: [{
                index: 0,
                message: {
                    role: 'assistant',
                    content: response
                },
                finish_reason: 'stop'
            }],
            usage: {
                prompt_tokens: promptTokens,
                completion_tokens: completionTokens,
                total_tokens: promptTokens + completionTokens
            }
        });
    }
    
    /**
     * 模拟流式API响应
     * @param {Array} messages 消息数组
     * @param {Function} resolve Promise解析函数
     */
    simulateStreamResponse(messages, resolve) {
        const lastMessage = messages[messages.length - 1].content;
        let response;
        
        if (lastMessage.includes('道路') || lastMessage.includes('勘察')) {
            response = "根据道路勘察规范，需要考虑地质条件、水文条件和周边环境等因素。建议进行详细的地质勘察，包括钻探取样和土壤分析，以确定道路基础设计参数。同时，应评估排水系统需求和潜在的环境影响。";
        } else if (lastMessage.includes('地质') || lastMessage.includes('岩石')) {
            response = "该区域主要岩石类型为砂岩和页岩，属于沉积岩类别。根据钻探数据，表层0-5米主要为粉质粘土和砂质土，5-15米为强风化砂岩，15米以下为中风化砂岩。地下水位在8-10米左右，季节性波动约1-2米。";
        } else if (lastMessage.includes('水文') || lastMessage.includes('排水')) {
            response = "该区域年均降雨量850mm，集中在6-9月份。根据径流计算，需要设计的排水系统应能应对50年一遇的暴雨强度，建议采用混凝土U型沟进行路面排水，断面尺寸建议不小于40cm×50cm，并设置沉砂池处理路面径流。";
        } else {
            response = "已收到您的问题，作为机勘院DeepSeek助手，我可以提供道路勘察、地质分析和工程设计相关的专业建议。请提供更多具体信息，以便我能给出更准确的专业回答。";
        }
        
        // 将响应分成多个部分，模拟流式传输
        const chunks = response.match(/.{1,10}/g) || [];
        
        // 模拟token使用统计
        const promptTokens = Math.ceil(lastMessage.length / 4);
        const completionTokens = Math.ceil(response.length / 4);
        
        this.tokenUsage.prompt += promptTokens;
        this.tokenUsage.completion += completionTokens;
        this.tokenUsage.total += (promptTokens + completionTokens);
        
        // 创建一个包含所有分块的控制器
        const controller = {
            content: '',
            chunks: chunks,
            currentIndex: 0,
            isComplete: false,
            response: {
                id: 'chatcmpl-' + Math.random().toString(36).substring(2, 12),
                object: 'chat.completion.chunk',
                created: Math.floor(Date.now() / 1000),
                model: this.defaultModel,
                choices: [{
                    index: 0,
                    delta: {
                        role: 'assistant',
                        content: ''
                    },
                    finish_reason: null
                }]
            },
            
            // 用于获取下一个分块
            next() {
                if (this.currentIndex < this.chunks.length) {
                    const chunk = this.chunks[this.currentIndex++];
                    this.content += chunk;
                    this.response.choices[0].delta.content = chunk;
                    
                    return {
                        done: false,
                        value: JSON.parse(JSON.stringify(this.response))
                    };
                } else if (!this.isComplete) {
                    this.isComplete = true;
                    this.response.choices[0].delta.content = '';
                    this.response.choices[0].finish_reason = 'stop';
                    
                    return {
                        done: false,
                        value: JSON.parse(JSON.stringify(this.response))
                    };
                } else {
                    return { done: true };
                }
            }
        };
        
        resolve({
            async: true,
            data: controller,
            controller: {
                abort: () => console.log('流式请求已中止')
            }
        });
    }
    
    /**
     * 获取用量统计数据
     * @returns {Object} 用量统计数据
     */
    getUsageStats() {
        // 实际环境中应该从API获取真实数据
        // 这里返回模拟数据
        return {
            monthly: {
                requests: 156248,
                tokens: 2560000,
                cost: 1284
            },
            daily: [
                { date: '3/1', requests: 1200, tokens: 76800 },
                { date: '3/2', requests: 1900, tokens: 121600 },
                { date: '3/3', requests: 1500, tokens: 96000 },
                { date: '3/4', requests: 1700, tokens: 108800 },
                { date: '3/5', requests: 2100, tokens: 134400 },
                { date: '3/6', requests: 1800, tokens: 115200 },
                { date: '3/7', requests: 2300, tokens: 147200 },
                { date: '3/8', requests: 2500, tokens: 160000 },
                { date: '3/9', requests: 2200, tokens: 140800 },
                { date: '3/10', requests: 2400, tokens: 153600 }
            ],
            models: [
                { name: 'DeepSeek Base', usage: 45 },
                { name: 'DeepSeek Pro', usage: 30 },
                { name: 'DeepSeek Expert', usage: 15 },
                { name: 'DeepSeek Coder', usage: 10 }
            ],
            departments: [
                { name: '系统管理部', usage: 15 },
                { name: '项目管理部', usage: 20 },
                { name: '道路勘察部', usage: 45 },
                { name: '数据分析部', usage: 20 }
            ]
        };
    }
    
    /**
     * 获取服务状态信息
     * @returns {Object} 服务状态信息
     */
    getServiceStatus() {
        // 实际环境中应该从API获取真实数据
        // 这里返回模拟数据
        return {
            apiConnection: 100,
            responseTime: 320,
            concurrentConnections: {
                current: 4,
                max: 10
            },
            errorRate: 0.05,
            recentErrors: [
                {
                    timestamp: '2025-03-10 14:23:15',
                    type: 'timeout',
                    description: '请求超过30秒未响应',
                    requestId: 'req_2a9d8f3e'
                },
                {
                    timestamp: '2025-03-09 09:45:22',
                    type: 'auth_error',
                    description: 'API密钥无效或已过期',
                    requestId: 'req_7b3e5f1c'
                }
            ]
        };
    }
}

// 创建全局DeepSeek连接器实例
const deepseekAPI = new DeepSeekConnector();

// 导出DeepSeek连接器
window.deepseekAPI = deepseekAPI; 